<?php

namespace app\api\controller;
use app\admin\model\WordsDetails;
use app\api\model\PhoneticSymbol;
use app\common\controller\Api;
use think\config\driver\Ini;
use think\Db;
use think\Request;

class Phonetic extends Api
{
    //如果$noNeedLogin为空表示所有接口都需要登录才能请求
    //如果$noNeedRight为空表示所有接口都需要验证权限才能请求
    //如果接口已经设置无需登录,那也就无需鉴权了
    //
    // 无需登录的接口,*表示全部
    protected $noNeedLogin = ['getWords','savewords'];
    // 无需鉴权的接口,*表示全部
    protected $noNeedRight = ['*'];

    //音标专练跟读设置 （get请求获取 post请求 更新）
    public function getUserSymbolSet()
    {
        $uid =  $this->auth->id;

        if($this->request->isGet()){
            $result = Db::table('fa_user')->where(['id'=>$uid])->field('id,symbol_set')->find();
        }else{
            $symbol_set = $this->request->post('symbol_set');
          
            $result['symbol_set']=$symbol_set;
            Db::table('fa_user')->where(['id'=>$uid])->update($result);

            $result['id']=$uid;
        }

        $this->success(null, $result);
    }

    public function getList()
    {
        $category = PhoneticSymbol::group('level3')->field('level3')->select();

        $result = [];
        foreach ($category as $c) {
            $list = PhoneticSymbol::where([
                'level3' => $c->level3,
            ])->select();

            $result[$c->level3] = $list;
        }

        $this->success(null, $result);
    }

    public function getInfo()
    {
        $id = request()->get("versionId");
        if (!$id)
            $this->error('参数有误');

        $info = PhoneticSymbol::where([
            'versionId' => $id,
        ])->find();
        $info['English'] = '';
        $info['Chinese'] = '';
        $this->success(null, $info);
    }


    public function files(){
        $directory = "/mnt/client2023/d-xueer.bigchun.com/xueer_houtai/public/file/phonetic_symbol/res";
        // 打开目录
        if ($handle = opendir($directory)) {

            // 遍历目录
            while (false !== ($file = readdir($handle))) {
                // 跳过特殊目录项 "." 和 ".."
                if ($file == '.' || $file == '..') {
                    continue;
                }
               var_dump( pathinfo($file, PATHINFO_EXTENSION));
                // 检查是否为jpg文件
//                if (strtolower(pathinfo($file, PATHINFO_EXTENSION)) == '') {
//                    // 获取不带后缀的文件名
//                    $filenameWithoutExt = pathinfo($file, PATHINFO_FILENAME);
//                    // 新的文件名，修改后缀
//                    $newFilename = $filenameWithoutExt . '.png';
//                    // 构建完整的旧文件和新文件路径
//                    $oldFilePath = $directory . $file;
//                    $newFilePath = $directory . $newFilename;
//
//                    // 重命名文件，修改后缀
//                    if (rename($oldFilePath, $newFilePath)) {
//                        echo "$file 后缀已成功改为 .png<br>";
//                    } else {
//                        echo "修改 $file 后缀时出错！请检查权限。<br>";
//                    }
//                }
            }

            // 关闭目录句柄
            closedir($handle);
        } else {
            echo "无法打开目录: $directory";
        }
    }
    public function getWords(){
        $id = request()->get("versionId");
        if (!$id)
            $this->error('参数有误');

        $info = WordsDetails::where([
            'versionId' => $id,
        ])->select();

        foreach ($info as $k => $value){
            $value['wordPic'] =request()->domain()."/file/phonetic_symbol/res/".$value['wordPic'];
            $value['wordFile'] =request()->domain()."/file/phonetic_symbol/res/".$value['wordFile'];
        }
        $this->success(null, $info);
    }

    public function savewords(){
                $res = WordsDetails::whereLike('wordPic',"%media/%")->select();
                foreach ($res as $key => $val){
                    $wordPic = pathinfo($val['wordPic'], PATHINFO_EXTENSION) == ''  ? $val['wordPic'].".png" : $val['wordPic'];
                    WordsDetails::where('wId',$val['wId'])->update(['wordPic'=>$wordPic]);
                }
    }

    public function saveFollow(){
        $data = $this->request->post();
        if (!$data['versionId'])
            $this->error('参数有误');
        $wordDetails = WordsDetails::where([
            'wId' => $data['wId'],
        ])->find();
        if(empty($wordDetails)) $this->error('单词不存在');
        $data['user_id'] = $this->auth->id;
        $res = Db::name('phonetic_log')
            ->where('versionId',$data['versionId'])
            ->where('user_id',$data['user_id'])
            ->where('wId',$data['wId'])
            ->find();
        $data['pretations'] = $wordDetails['pretations'];
        $data['symbol'] = $wordDetails['symbol'];
        $data['words'] = $wordDetails['words'];
        $data['updatetime'] =time();
        if($res){
            $res = Db::name('phonetic_log')->where('id',$res['id'])->update($data);
        }else{
            $res = Db::name('phonetic_log')->insert($data);
        }
        if($res){
            $this->success('保存成功');
        }else{
            $this->error('保存失败');
        }
    }

    public function getLog(){
   
        $data = $this->request->param();
        if (!$data['versionId'])
            $this->error('参数有误');
        $log= Db::name('phonetic_log')
            ->where('versionId',$data['versionId'])
            ->where('user_id',$this->auth->id)
            ->select();
        foreach ($log as &$v){
            $v['video_domain'] = NULL;
            if($v['video']) {
                $v['video_domain']= \request()->domain().$v['video'];
            }


            $wordsRel = Db::table('fa_words_details')->where(['wId'=>$v['wId']])->order('wId desc')->find();
            $v['wordFile'] = NULL;
            if($wordsRel['wordFile']){
                //$v['wordFile']= \request()->domain().$wordsRel['wordFile'];
               $v['wordFile']= \request()->domain().'/file/phonetic_symbol/res/'.$wordsRel['wordFile'];
            }

            $v['sentences']= NULL;;
            if($wordsRel['sentences']){
                $v['sentences']= $wordsRel['sentences'];
            }

            $v['wordPic']= NULL;;
            if($wordsRel['wordPic']){
                $v['wordPic']= \request()->domain().'/file/phonetic_symbol/res/'.$wordsRel['wordPic'];
                //$v['wordPic']= \request()->domain().$wordsRel['wordPic'];
            }
        }
       $this->success('',$log);
    }
    public function saveWork(){
        $data = $this->request->post();
        if (!$data['versionId'])
            $this->error('参数有误');
        $phonetic = PhoneticSymbol::where([
            'versionId' => $data['versionId'],
        ])->find();
        if(empty($phonetic)) $this->error('单词不存在');
        $log= Db::name('phonetic_log')
            ->where('versionId',$data['versionId'])
            ->where('user_id',$this->auth->id)
            ->select();
        foreach ($log as &$v){
            $v['video'] = request()->domain().$v['video'];
        }
        $score = Db::name('phonetic_log')
            ->where('versionId',$data['versionId'])
            ->where('user_id',$this->auth->id)
            ->avg('score');
        $green = $yellow = $red = 0;
        foreach ($log as $key => $value){
            if ($value['score'] > 80){
                $green+=1;
            }
            if ($value['score'] > 60 && $value['score'] < 80){
                $yellow+=1;
            }
            if ($value['score'] < 60){
                $red+=1;
            }
        }
        $data = [
            'title' => $phonetic['level3'].'-['.$phonetic['symbols']."]",
            'module'=>'音标专练',
            'user_id' => $this->auth->id,
            'score'=>$score,
            'mission_type'=>2,
            'mission_id'=>0,
            'use_time'=> $this->timestampToStr($data['use_time']),
            'question_num'=>count($log),
            'green' =>$green,
            'yellow' =>$yellow,
            'red' =>$red,
            'json' => json_encode($log),
        ];
        // 获取本月开始时间戳
       // $startOfMonth = mktime(0, 0, 0, date('m'), 1, date('Y'));

// 获取本月结束时间戳
        //$endOfMonth = mktime(23, 59, 59, date('m'), date('t'), date('Y'));

// 将时间戳保存到$data数组中
        /*$info = Db::name('reciting_mission')
            ->where('user_id',$this->auth->id)
            ->where('mission_type',2)
            ->where('mission_id',0)
            ->where('title',$data['title'])
            ->whereBetween('createtime',[$startOfMonth,$endOfMonth])
            ->find();
        if($info){
            $data['updatetime'] = time();
            $res = Db::name('reciting_mission')->where('id',$info['id'])->update($data);
        }else{*/
            $data['createtime'] = time();
            $data['updatetime'] = time();
            $res = Db::name('reciting_mission')->insert($data);
        //}
        if ($res){
            $data['json'] = $log;
            $this->success('保存成功',$data);
        }else{
            $this->error('保存失败');
        }
    }


    function timestampToStr($timestamp) {
        // 计算小时数
        $hours = intval(($timestamp / 3600));
        // 计算分钟数
        $minutes = intval((($timestamp - ($hours * 3600)) / 60));
        // 计算秒数
        $seconds = $timestamp - ($hours * 3600) - ($minutes * 60);

        $result = '';
        // 如果有小时，添加到结果中
        if ($hours > 0) {
            $result .= str_pad($hours, 2, '0', STR_PAD_LEFT) . 'h';
        }
        // 如果有分钟，添加到结果中
        if ($minutes > 0) {
            $result .= str_pad($minutes, 2, '0', STR_PAD_LEFT) . 'min';
        }
        // 如果有秒，添加到结果中
        if ($seconds > 0) {
            $result .= str_pad($seconds, 2, '0', STR_PAD_LEFT) . 's';
        }

        return $result;
    }
}